import React, { PureComponent } from 'react';
import { connect } from 'dva';
import 'antd-mobile/lib/image-picker/style'
import { Modal, Carousel, List, Button } from "antd-mobile"
import MToast from "../../Util/MToast"
import { isNull, getUUID, handleOSS, handleImg } from "../../../utils/helper"
import { handleUrl } from "../../../utils/request"
import lrz from "lrz";
import moment from "moment"
//test合并分支
class MyUploadImgNew extends PureComponent {
	constructor(props) {
		super(props);
		let value = this.props.value;
		this.uploadInput = null;
		this.state = {
			value: value,
			previewVisible: false,
			previewImg: "",
			btnHide: false
		}
	}
	componentWillReceiveProps(nextProps) {
		// Should be a controlled component.
		if ('value' in nextProps) {
			let value = nextProps.value;
			this.setState({
				value
			});
		}
	}
	changeValue = (val) => {
		if (!('value' in this.props)) {
			this.setState({
				value: val
			});
		}
		this.triggerChange(val);
	};
	triggerChange = (changedValue) => {
		const onChange = this.props.onChange;
		if (onChange) {
			onChange(changedValue);
		}
	};
	getFileName = (subfix) => {
		return "/" + MI_APP_CODE + "/" + moment().format("YYYYMMDD") + "/" + getUUID() + ".png"
	}
	uploadFunc = (e) => {
		this.setState({
			btnHide: false
		});
		let { dispatch, max_size, field, action } = this.props;
		if (isNull(action)) {
			// action="http://img.tms.xuanit.com/upload.php"
			action = API_URL + "/upload"
		}
		let uploadId = "upload_" + field[0];
		max_size = isNull(max_size) ? 5 : max_size * 1;
		let that = this;
		let files = e.target.files;
		//e.target.files是个数组 多选时 需要遍历 然后一个一个的上传
		let newFiles = [];
		for (let i = 0; i < files.length; i++) {
			let file = files[i];
			let size = file.size / (1024 * 1024);//kb
			if (size > max_size) {
				MToast.fail(file.name + "文件过大，文件最大" + max_size + "Mb", 1.5, null, false);
			}
			else {
				newFiles.push(file)
			}
		}
		files = newFiles;
		let len = files.length;
		let { max, value } = that.props;
		max = isNull(max) ? 5 : max * 1;
		let valLen = 0;
		let isMax = false;
		if (isNull(value)) {
			valLen = 0;
		}
		else {
			valLen = value.split(",").length;
		}
		if (len >= max - valLen) {
			len = max - valLen;
			isMax = true;
		}
		for (let i = 0; i < len; i++) {
			let file = files[i];
			let size = file.size;
			let quality = 1;
			if (size > 1024 * 50) {//大于100kb时再压缩为100kb
				quality = size / (1024 * 50)
			}
			lrz(file, { quality }).then(rst => {
				let newFile = rst.file;
				// return;
				let file_name = file.name;
				let onlineFileName = this.getFileName(file_name);
				let FD = new FormData();
				// FD.append("fileName",onlineFileName);
				FD.append(onlineFileName, newFile);
				FD.append("token", localStorage[MI_APP_CODE+"mi_token"]);
				dispatch({
					type: "form/upload",
					payload: {
						url: action,
						params: FD,
						callback: (result) => {
							if (result.error) {
								MToast.fail(file_name + " 上传失败！", 1.5, null, false);
							}
							else {
								MToast.success(file_name + " 上传成功！", 1.5, null, false);
								// let {thumbUrl,url}=result;
								let url = onlineFileName;
								let { value } = that.state;
								if (isNull(value)) {
									value = url;
								}
								else {
									value = value + "," + url
								}
								that.changeValue(value);
								let dom = document.getElementById(uploadId);
								if (!isNull(dom)) {
									dom.value = ""
								}
							}
						}
					}
				})
			})
		}
		if (isMax) {
			this.setState({
				btnHide: true
			});
			if (len > max - valLen) {
				setTimeout(() => {
					MToast.fail("最大上传: " + max + "，超出的未上传", 1.5, null, false);
				})
			}
		}
	};
	componentDidMount() {
		if (!isNull(this.uploadInput)) {
			this.uploadInput.addEventListener("change", this.uploadFunc, false)
		}
	}

	onPreview = (file, isPdf) => {
		if (isPdf) {
			window.open(file, "_blank")
		}
		else {
			this.setState({
				previewVisible: true,
				previewImg: file
			})
		}
	};
	onRemove = (file) => {
		// Modal.alert()
		let { value } = this.state;
		let val = value.split(",");
		val = val.filter(item => item !== file);
		val = val.join(",");
		this.changeValue(val);
	};
	handleCancel = () => {
		this.setState({
			previewVisible: false
		})
	};
	upload = () => {
		this.uploadInput.click()
	};
	previewImgLists = (currentIndex) => {
		let { value } = this.state;
		value = value.split(",");
		value = value.map(i => {
			return handleImg(i);
		})
		if (browser.isInApp) {
			//index 当前索引 number， imgs:["",""] 所有图片  array，download:是否可以下载 bool
			Func.callHander(bridge, "gallery", { index: currentIndex, imgs: value, download: true });
		}
		else {
			this.setState({
				previewVisible: true,
				previewImg: value[currentIndex],
				previewIndex: currentIndex
			})
		}
	}
	renderImg = (value, isDisabled, isReadonly) => {
		if (isNull(value) || value.length == 0) {
			return null
		}
		else {
			value = value.split(",");
			let imgs = [];
			value.map((item, key) => {
				let newItem = item;
				newItem = handleImg(newItem);
				if (isDisabled || isReadonly) {
					newItem = newItem + "_120"
				}
				let pdfIndex = newItem.indexOf(".pdf");
				let isPdf = false;
				if (pdfIndex != -1) {
					if ((pdfIndex + 4) === newItem.length) {//是pdf
						isPdf = true
					}
				}
				imgs.push(
					<div className="mi-upload-img-img" key={newItem} style={{ top: "-4px" }} onClick={() => {
						this.previewImgLists(key);
					}}>
						{
							!isDisabled && !isReadonly && <div className="am-image-picker-item-remove" onClick={(e) => {
								e.preventDefault();
								e.stopPropagation();
								this.onRemove(item)
							}} >
								x
							</div>
						}
						<div style={{ width: "72px", height: "72px" }} data-flex>
							<img src={isPdf ? "image/pdf.jpg" : newItem} />
						</div>
						<span className="ant-upload-list-item-actions">
							<i className="anticon anticon-eye-o" onClick={() => this.onPreview(newItem, isPdf)} />
						</span>
					</div>
				)
			});
			return imgs
		}
	};
	dataURLtoBlob = (dataurl) => {
		let arr = dataurl.split(',');
		let mime = arr[0].match(/:(.*?);/)[1];
		let bstr = atob(arr[1]);
		let n = bstr.length;
		let u8arr = new Uint8Array(n);
		while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}
		return new Blob([u8arr], { type: mime });
	}
	blobToFile = (theBlob, fileName) => {
		theBlob.lastModifiedDate = new Date();
		theBlob.name = fileName;
		return theBlob;
	}
	callbackTakePhotos = (file) => {
		let blob = this.dataURLtoBlob("data:image/png;base64," + file.file);
		file = this.blobToFile(blob, "图片");
		this.uploadFunc({
			target: {
				files: [file]
			}
		})
	}
	callbackChoicePhotos = (file) => {
		//file 类型为"['','']"
		let fileList = [];
		let files = file.files;
		files = JSON.parse(files);
		files.map(item => {
			let blob = this.dataURLtoBlob("data:image/png;base64," + item);
			item = this.blobToFile(blob, "图片");
			fileList.push(item);
		})
		this.uploadFunc({
			target: {
				files: fileList
			}
		})
	}
	appPhotos = (props) => {
		// 类型 是否多选 最多选择几张 当前有多少张
		let { photos_type = 1, isMulti, max, current } = props;
		Func.registerHanderBridge("callbackChoicePhotos", this.callbackChoicePhotos);
		Func.callHander(bridge, "choicePhotos", { type: photos_type, option: { isMulti: true, total: max, current } });
	}
	renderUploadBtn = (isShowBtn, uploadId, isMulti, photos_type, max) => {
		if (isShowBtn) {
			if (browser.isInApp) {
				let { value } = this.state;
				let imgLen = 0;
				if (isNull(value)) {
					imgLen = 0
				}
				else {
					imgLen = value.split(",").length;
				}
				return (
					<div className="mi-upload-img-btn" onClick={() => {
						this.appPhotos({ photos_type, isMulti, max, current: imgLen })
					}}>
					</div>
				)
			}
			else {
				return (
					<div className="mi-upload-img-btn">
						<input
							name="a"
							id={uploadId}
							type="file"
							ref={e => this.uploadInput = e}
							multiple={isMulti}
							accept="image/*"
							capture={photos_type == 1}
						/>
					</div>
				)
			}
		}
		else {
			return null;
		}

	}
	render() {
		let { disabled, readonly, min = 0, max = 5, max_size = 5, multiple = 0, photos_type = 1, field, accept, tips } = this.props;
		//photos_type 0 拍照和选择相册 1只能拍照 2只能选择相册
		accept = isNull(accept) ? "image/*,application/pdf" : accept;
		let uploadId = "upload_" + field[0];
		min = isNull(min) ? 0 : min * 1;
		max = isNull(max) ? 5 : max * 1;
		max_size = isNull(max_size) ? 5 : max_size * 1;
		let isMulti = multiple == 1;
		let { previewVisible, previewImg, value, previewIndex, btnHide } = this.state;
		let isDisabled = disabled == 1;
		let isReadonly = readonly == 1;
		let uploadClass = "clearfix mi-upload-img";
		if (isDisabled || isReadonly) {
			uploadClass += " disabled"
		}
		let imgLen = 0;
		if (isNull(value)) {
			imgLen = 0
		}
		else {
			imgLen = value.split(",").length;
		}
		let isShowBtn = imgLen < max;
		isShowBtn = isShowBtn && !isDisabled && !isReadonly;
		if (btnHide && isShowBtn) { //按钮隐藏之后又出现了
			setTimeout(() => {
				this.uploadInput.removeEventListener("change", this.uploadFunc, false);
				this.uploadInput.addEventListener("change", this.uploadFunc, false);
			})
		}
		return (
			<div className="am-image-picker" >
				<div className="am-image-picker-list" role="group">
					<div className="mi-upload-img-wrapper">
						{this.renderImg(value, isDisabled, isReadonly)}
						{this.renderUploadBtn(isShowBtn, uploadId, isMulti, photos_type, max)}
					</div>
				</div>

				<Modal
					visible={previewVisible}
					closable
					className="mi-upload-img-modal"
					onClose={() => {
						this.setState({
							previewVisible: false
						})
					}}
				>
					<Carousel
						autoplay={false}
						infinite={false}
						selectedIndex={previewIndex}
					>
						{value && value.split(",").map(val => (
							<a
								key={val}
								style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
							>
								<img
									src={`${handleImg(val)}`}
									alt=""
									style={{ width: '100%', verticalAlign: 'center' }}
									onLoad={() => {
										// fire window resize event to change height
										window.dispatchEvent(new Event('resize'));
										this.setState({ imgHeight: 'auto' });
									}}
								/>
							</a>
						))}
					</Carousel>
				</Modal>
				<Modal
					popup
					visible={false}
					animationType="slide-up"
				>
					<List className="popup-list">
						{['拍照', '照片'].map((i, index) => (
							<List.Item key={index}>{i}</List.Item>
						))}
						<List.Item>
							取消
            </List.Item>
					</List>
				</Modal>
			</div>
		)
	}
}
//111
export default MyUploadImgNew;